package com.etc.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.etc.dao.UserinfoDao;
import com.etc.pojo.Userinfo;
import com.etc.utils.DBUtil;

/**
 * UserinfoDao接口的实现类 操作数据库
 * 
 * @author Administrator
 *
 */
public class UserinfoDaoImpl implements UserinfoDao {

	@Override
	public int insert(Userinfo userinfo) {

		return DBUtil.doUpdate("insert into userinfo values(null,?,?,?)", userinfo.getUsername(),
				userinfo.getPassword(), userinfo.getAge());
	}

	@Override
	public Userinfo queryByUsernameAndPwd(String username, String password) {
		Userinfo userinfo = null;
		ResultSet resultSet = DBUtil.doQuery("select * from userinfo where username = ? and password = ?", username,
				password);

		try {
			while (resultSet.next()) {
				int userId = resultSet.getInt("user_id"); // user_id 参数是数据库表中的列名
				int age = resultSet.getInt("age");
				userinfo = new Userinfo(userId, username, password, age);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userinfo;
	}

	@Override
	public int update(Userinfo userinfo) {
		return DBUtil.doUpdate("update userinfo set password = ?,age = ? where user_id = ?", userinfo.getPassword(), userinfo.getAge(), userinfo.getUserId());
	}

	@Override
	public int updatePassword(Integer userId, String password) {
		return DBUtil.doUpdate("update userinfo set password = ? where user_id = ?", password, userId );
	}

	@Override
	public int delete(Integer userId) {
		// TODO Auto-generated method stub
		return DBUtil.doUpdate("delete from userinfo where user_id = ?", userId );
	}

	@Override
	public Userinfo queryByUsername(String username) {
		Userinfo userinfo = null;
		ResultSet resultSet = DBUtil.doQuery("select * from userinfo where username = ?", username);

		try {
			while (resultSet.next()) {
				int userId = resultSet.getInt("user_id"); // user_id 参数是数据库表中的列名
				String password = resultSet.getString("password");
				int age = resultSet.getInt("age");
				userinfo = new Userinfo(userId, username, password, age);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userinfo;
	}

	@Override
	public Userinfo queryById(Integer userId) {
		Userinfo userinfo = null;
		ResultSet resultSet = DBUtil.doQuery("select * from userinfo where user_id = ?", userId);

		try {
			while (resultSet.next()) {
				String username = resultSet.getString("username");
				String password = resultSet.getString("password");
				int age = resultSet.getInt("age");
				userinfo = new Userinfo(userId, username, password, age);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userinfo;
	}

}
